package app.qrcode.browser.chat.adapter

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import app.qrcode.browser.chat.MyApplication.Companion.context
import app.qrcode.browser.chat.R
import app.qrcode.browser.chat.activities.AskChatActivity

/**
 * Created by DomenCai on 2022/3/11.
 */
class ContactAdapter :
    RecyclerView.Adapter<ContactAdapter.ViewHolder>() {

    private val contactList: MutableList<Contact> = mutableListOf()


    fun updateList(newList: List<Contact>) {
        contactList.clear()
        contactList.addAll(newList)
        notifyDataSetChanged()
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val contactPhoto: ImageView = view.findViewById(R.id.contactPhoto)
        val contactName: TextView = view.findViewById(R.id.contactName)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.contact_item, parent, false)
        val viewHolder = ViewHolder(view)


        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.bindingAdapterPosition
            val contact = contactList[position]
            if (contact.type == Contact.ITEM_ADD) {
                val intent = Intent(context, AskChatActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                context.startActivity(intent)
            } else {
                Toast.makeText(context, "fuckyou", Toast.LENGTH_SHORT).show()
            }
        }


        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val contact = contactList[position]
        holder.contactPhoto.setImageResource(contact.type)
        holder.contactName.text = contact.name
    }

    override fun getItemCount(): Int = contactList.size


}